package com.zsguan.z.zhttp4andr;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by chshqiang on 14-12-1.
 * api基类
 */
public abstract class Zapi<T> {
    /**
     * 返回数据结构为一个对象
     */
    public static final int TYPE_OBJECT = 0;
    /**
     * 返回数据结构为一个集合
     */
    public static final int TYPE_ARRAY = 1;
    /**
     * 返回数据结构为字符串
     */
    public static final int TYPE_STRING = 2;
    /**
     * 无返回值
     */
    public static final int TYPE_NOR = 3;

    /**
     * 返回数据回调接口
     */
    protected ApiCallBack<T> callBack;

    /**
     * 请求连接
     */
    protected String url;

    /**
     * 请求参数
     */
    protected Map<String, String> mRequestBody;

    public Zapi(ApiCallBack<T> callBack, String domain, String api) {

        this.url = domain + api;

        this.callBack = callBack;
    }

    /**
     * 设置参数
     *
     * @param params 参数集合
     */
    public Zapi setParams(Map<String, String> params) {
        if (null != params && !params.isEmpty()) {
            int size = params.size();
            mRequestBody = new HashMap<>(size);
            mRequestBody.putAll(params);
        }

        return this;
    }

    /**
     * 获取请求返回数据结构类型
     *
     * @return 数据结构类型，见{@link #TYPE_OBJECT}、{@link #TYPE_ARRAY}，默认为{@link #TYPE_OBJECT}
     */
    public int getType() {
        return TYPE_OBJECT;
    }

    /**
     * 获取是否缓存
     *
     * @return true: 是
     */
    public boolean isCache() {
        return false;
    }

    /**
     * @return 获取该接口在缓存中的key值
     */
    public String getCacheKey() {
        return this.url;
    }

    /**
     * 获取缓存{@link SharedPreferences}对象
     *
     * @return {@link SharedPreferences}对象
     */
    public SharedPreferences getSharedPreferences() {
        return null;
    }

    /**
     * @return 获取该接口最新返回的缓存数据
     */
    public String getCacheData() {
        if (isCache()) {
            return getSharedPreferences().getString(getCacheKey(), "");
        }

        return "";
    }

    public T get() {
        String cacheData = getCacheData();

        if (!TextUtils.isEmpty(cacheData)) {
            onCallback(cacheData);
        }

        T t = null;
        switch (getType()) {
            case TYPE_NOR:
                ZHttpUrlConnection.post(url, mRequestBody, 15000);
                break;
            case TYPE_OBJECT:
            case TYPE_ARRAY:
            case TYPE_STRING:
            default:
                String result = ZHttpUrlConnection.post(url, mRequestBody, 15000, 15000);
                t = parseJson(result);
                break;
        }

        return t;
    }

    private String post() {
        String cacheData = getCacheData();

        if (!TextUtils.isEmpty(cacheData)) {
            onCallback(cacheData);
        }

        String result = null;
        switch (getType()) {
            case TYPE_NOR:
                ZHttpUrlConnection.post(url, mRequestBody, 15000);
                break;
            case TYPE_OBJECT:
            case TYPE_ARRAY:
            case TYPE_STRING:
            default:
                result = ZHttpUrlConnection.post(url, mRequestBody, 15000, 15000);
                break;
        }

        return result;
    }

    public void start() {
        new AsyncTask<Object, Void, String>() {

            @Override
            protected String doInBackground(Object... params) {
                return Zapi.this.post();
            }

            @Override
            protected void onPostExecute(String result) {
                if (null != callBack) {
                    onCallback(result);
                }
            }

        }.execute();
    }

    private void onFailure(String error) {
        // todo 打印错误
        // todo 回调接口
    }

    private void onCallback(String json) {
        T t = parseJson(json);

        if (null == t) {
            callBack.onFailure(new Exception("Data is NULL"), 0, "Data is NULL");
        } else {
            if (isCache()) {
                SharedPreferences preferences = getSharedPreferences();
                preferences.edit().putString(getCacheKey(), json).apply();
            }

            callBack.onSuccess(t);
        }
    }

    /**
     * 取消请求
     */
    public void cancel() {
        // todo 取消连接
    }

    public void clear() {
        mRequestBody.clear();

        mRequestBody = null;
    }

    protected T parseJson(String json) {
        return (T) json;
    }

}
